/**
 * @Grup:PACKAGE_NAME
 * @Auther:cola
 * @Data:2021/3/30-2021-03-21:41
 * @version:1.0
 *
 * join方法:
 * 加入线程,让调用方法的线程先执行指时间或执行完毕
 * 中断线程:
 * (1)使用interrupt方法中断线程,设置一个中断状态(标记)
 * (2)自定义标记的方式
 */
public class threadDemo2 {
    public static void main(String[] args) {
        MyRunnable2 mr2= new MyRunnable2();
        Thread t=new Thread(mr2);
        //t.start();
        MyRunable3 mr3=new MyRunable3();
        Thread t2=new Thread(mr3);
        t2.start();

        for (int i = 19; i <50 ; i++) {
            System.out.println(Thread.currentThread().getName()+"--"+i);
            try {
                Thread.sleep(300);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (i==20){
                /*try {
                    t.join();//先让t线程执行完毕
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }*/
                //t.interrupt();//中断线程,只是做了一个中断标记
                mr3.flag=false;
            }
        }

    }
}

class  MyRunnable2 implements Runnable{
    @Override
    public void run() {
        for (int i = 19; i <50 ; i++) {
            if (Thread.interrupted()){//测试中断状态,此方法会把中断状态清除
                break;
            }
            System.out.println(Thread.currentThread().getName()+"--"+i);
            try {
                Thread.sleep(300);
            } catch (InterruptedException e) {
                e.printStackTrace();
                Thread.currentThread().interrupt();
            }
        }
    }
}
class MyRunable3 implements Runnable{
    public boolean flag=true;
    @Override
    public void run() {
        int i=0;
        while (flag){
            System.out.println(Thread.currentThread().getName()+"==="+(i++));
            try {
                Thread.sleep(300);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    public MyRunable3(){
        flag=true;
    }
}
